package com.usian.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usian.article.entity.ApCollection;
import com.usian.article.mapper.ApCollectionMapper;
import com.usian.article.service.IApCollectionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.threadlocal.UserThreadLocalUtils;
import com.usian.model.behavior.dtos.CollectionBehaviorDto;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP收藏信息表 服务实现类
 * </p>
 *
 * @author usian
 * @since 2022-07-19
 */
@Service
public class ApCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements IApCollectionService {
    //收藏行为
    @Override
    public void collection(CollectionBehaviorDto dto) {
        //1、参数校验
        if(dto==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2、获取用户id，判断用户是否登录
        boolean isUser = false;
        Integer userId = UserThreadLocalUtils.getUserId();
        if(userId!=null && userId!=0){
            //用户是登录状态
            isUser=true;
        }

        if(userId==null && dto.getEquipmentId()==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE,"用户id和设备id不能同时为空");
        }

        //3、查询用户或设备针对当前文章是否已经收藏
        QueryWrapper<ApCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApCollection::getArticleId,dto.getArticleId());
        if(isUser){
            //登录状态，根据用户id查询
            queryWrapper.lambda().eq(ApCollection::getApUserId,userId);
        }else{
            //未登录状态，根据设备号查询
            queryWrapper.lambda().eq(ApCollection::getEquipmentId,dto.getEquipmentId());
        }

        ApCollection apCollection = this.getOne(queryWrapper);
        if(apCollection==null){
            //3.1 如果未收藏，记录收藏行为
            apCollection = new ApCollection();
            if(isUser){
                apCollection.setApUserId(userId);
            }else{
                apCollection.setEquipmentId(dto.getEquipmentId());
            }
            apCollection.setArticleId(dto.getArticleId());
            apCollection.setOperation(dto.getOperation());
            apCollection.setType(dto.getType());
            apCollection.setCollectionTime(new Date());
            apCollection.setPublishedTime(dto.getPublishedTime());
            this.save(apCollection);
        }else{
            //3.2 如果已经收藏，更新点赞收藏
            apCollection.setOperation(dto.getOperation());
            updateById(apCollection);
        }
    }
}
